import React, {
  useState,
  forwardRef,
  useImperativeHandle,
} from 'react'
import {
  http,
  UdModalForm,
  validators,
} from '@/lib'
import userAPI from '@/apis/UserManagement'
import apis from '@/apis'
import UdSelect from '@/components/UdFormControls/UdSelect'
import NotFoundContent from '@/components/NotFoundContent'
import {
  Icon,
  Spin,
  TreeSelect,
} from 'antd'
import { WrappedFormUtils } from 'antd/lib/form/Form'

let modalForm: WrappedFormUtils;
let fetchTimer: any = null;

export default forwardRef(function AddStaffArea(props: any, ref: any) {

  useImperativeHandle(ref, () => ({
    initData,
  }))
  const {
    info,
    brandList,
  }: any = props;

  const [querying, setQuerying] = useState(false)
  const [customerCodes, setCustomerCodes] = useState<any>([])
  const [customerNames, setCustomerNames] = useState<any>([])
  const [treeData, setTreeData] = useState<any>([])

  const getCustomerList = async (params) => {
    setQuerying(true)
    try {
      const customerRes: any = await http.post(userAPI.getStaffList, params)
      setQuerying(false)

      return customerRes
    } catch (error) {
      setQuerying(false)
      return []
    }
  }

  /* 节流获取搜索的经销商 */
  const fetchCustomerHandle = (value: String, type: String) => {
    if (!value) return

    if (fetchTimer) {
      clearTimeout(fetchTimer)
      fetchTimer = null;
    }

    fetchTimer = setTimeout(async () => {
      if (type === 'code') {

        setCustomerCodes([])
        const { data }: any = await getCustomerList({ userCode: value })
        setCustomerCodes(data)
      } else if (type === 'name') {
        setCustomerNames([])
        const { data }: any = await getCustomerList({ realName: value })
        setCustomerNames(data)
      }
    }, 500)
  }

  const customerChangeHandle = (val: any, type: String) => {
    if (!val) return;

    const options = type === 'code' ? customerCodes : customerNames;
    const params = type === 'code' ? { realName: val } : { userCode: val }

    modalForm.setFieldsValue(params)
    type === 'code' ? setCustomerNames(options) : setCustomerCodes(options)
  }

  const formatTreeData = (arr: any[]): any[] => arr.map((a: any) => ({
    value: a.code,
    title: a.name,
    children: a.children && a.children.length ? formatTreeData(a.children) : []
  }))

  const getTreeByUser = (brandCode: string) => {
    http.get(apis.getTreeByUser, { params: { organizationCode: brandCode } }).then(({ data }: any) => {
      setTreeData([...formatTreeData(data.children || [])])

      modalForm.setFieldsValue({'districtCode': []})
    })
  }

  const initSelectOptions = async () => {
    const { data }: any = await getCustomerList({ userCode: info.userCode })
    setCustomerNames(data)
  }

  const initData = () => {
    modalForm.setFieldsValue({
      userCode: info.userCode,
      realName: info.userCode,
      brandCode: info.brandCode,
      districtCode: info.districtCode ? info.districtCode.split(',') : [],
    })

    http.get(apis.getTreeByUser, { params: { organizationCode: info.brandCode } }).then(({ data }: any) => {
      setTreeData([...formatTreeData(data.children || [])])
    })

    initSelectOptions()
  }

  return (
    <div>
      <UdModalForm
        {...props}
        getForm={(form) => (modalForm = form)}
        items={[
          {
            label: '员工编码',
            id: 'userCode',
            rules: [validators.required],
            render: () => (
              <UdSelect
                disabled={!!info}
                showSearch
                notFoundContent={querying ? <Spin size="small" /> : <NotFoundContent />}
                onSearch={(val) => fetchCustomerHandle(val, 'code')}
                onChange={(val, option) => customerChangeHandle(val, 'code')}
                placeholder='请输入员工编码搜索'
                suffixIcon={<Icon type='search' />}
                className='ud-search-select'
                options={customerCodes}
                mapping={{value: 'userCode', title: 'userCode'}}
              />
            ),
          },
          {
            label: '员工姓名',
            id: 'realName',
            rules: [validators.required],
            render: () => (
              <UdSelect
                disabled={!!info}
                showSearch
                notFoundContent={querying ? <Spin size="small" /> : <NotFoundContent />}
                onSearch={(val) => fetchCustomerHandle(val, 'name')}
                onChange={(val, e) => customerChangeHandle(val, 'name')}
                placeholder='请输入员工姓名搜索'
                suffixIcon={<Icon type='search' />}
                className='ud-search-select'
                options={customerNames}
                mapping={{value: 'userCode', title: 'realName'}}
              />
            ),
          },
          {
            label: '所属品牌公司',
            id: 'brandCode',
            rules: [validators.required],
            render: () => (
              <UdSelect
                options={brandList}
                placeholder="请选择授权管理区域"
                onChange={(e: any) => getTreeByUser(e)}
              />
            )
          },
          {
            label: '授权管理区域',
            id: 'districtCode',
            rules: [validators.required],
            render: () => (
              <UdTreeSelect
                multiple
                treeData={treeData}
                treeCheckable
                placeholder="请选择授权管理区域"
                dropdownStyle={{ maxHeight: 600 }}
              />
            )
          },
        ]}
      />
    </div>
  )
})


function UdTreeSelect(props) {
  const { treeData, className, children, ...rest } = props
  return (
    <TreeSelect
      className={className}
      getPopupContainer={(triggerNode) => triggerNode}
      treeData={treeData}
      showCheckedStrategy={TreeSelect.SHOW_PARENT}
      {...rest}
    >
      {!treeData && props.children}
    </TreeSelect>
  )
}